package com.example.qqfake;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ChatActivity extends AppCompatActivity {
    private final String serverAddress = "192.168.104.215";
    private final int serverPort = 50000;

    public  Socket socket;
    private PrintWriter out;
    private BufferedReader in;

    private EditText content;
    private Button send;
    private ImageView exit_chat;
    private User user;
    private List<Chat_content> list = new ArrayList<>();
    private MyAdapter adapter = new MyAdapter(list);
    private int i=0;//记录聊天条数
    private String myid;
    private TextView your_name;
    private String goal_id;
    private String goal_name;
    private String first_content;
    private  AlertDialog.Builder builder1;
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_chat);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        //数据从数据库中获得，同时还要获取对话对象的唯一id
        // 获取SharedPreferences实例，文件名为"myPreferences"，与MainActivity中使用的文件名相同
        SharedPreferences sharedPreferences = getSharedPreferences("myPreferences", Context.MODE_PRIVATE);
        // 读取数据，键为"User_id"
        myid = sharedPreferences.getString("User_id","hhh");
        int myidid = Integer.parseInt(myid);
        user=new User(myidid);
        // 创建一个AlertDialog的构建器
        builder1 = new AlertDialog.Builder(this);




        //从Intent中读取要聊天的对象
        Intent intent = getIntent();
        goal_id = intent.getStringExtra("chat_partner");
        goal_name = intent.getStringExtra("chat_name");

        if(intent.hasExtra("content")){
            first_content = intent.getStringExtra("content");
            //显示
            //此处图片为对话对象的头像，也是从数据库中拿
            Chat_content p1 = new Chat_content(Chat_content.TYPE_ONE,first_content,R.drawable.left);
            // 通知适配器新元素添加
            adapter.addItem(p1,i);
            i++;
            Log.v("msg","receiver");

        }


        //绑定控件
        content = findViewById(R.id.content);
        send = findViewById(R.id.send);
        your_name = findViewById(R.id.your_name);
        your_name.setText(goal_name);
        exit_chat = findViewById(R.id.exit_chat);

        RecyclerView recyclerView = findViewById(R.id.rv);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);

        recyclerView.setLayoutManager(linearLayoutManager);


        adapter = new MyAdapter(list);
        recyclerView.setAdapter(adapter);


        //子线程开启socket发送连接请求，不停监听信息
        new Thread(()->{
            try {
                socket= new Socket(serverAddress, serverPort);
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                out= new PrintWriter(socket.getOutputStream(), true);
                //给服务器发送一条在线提示

                Date now = new Date();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String formattedString = formatter.format(now);
                String message = "8,"+myid+","+formattedString+","+myid+"online"+","+myid;
                out.println(message);


                // 启动读取消息的线程
                new Thread(this::readMessages).start();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }).start();



        exit_chat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ChatActivity.this, MainActivity.class);
                startActivity(intent);
                ChatActivity.this.finish();

            }
        });


        send.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){

                //子线程发送消息
                Date now = new Date();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String formattedString = formatter.format(now);
                String message = "2,"+myid+","+formattedString+","+content.getText().toString()+","+goal_id;

                Thread thread = new Thread(new Worker(message));
                thread.start();
                //此处图片需要读取数据库中的头像
                Chat_content p1 = new Chat_content(1,content.getText().toString(),R.drawable.right);
                // 通知适配器新元素添加
                adapter.addItem(p1,i);
                i++;
                content.setText("");
                Log.v("msg","send");

            }

        });


    }


    public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        private List<Chat_content> items;

        public MyAdapter(List<Chat_content> items) {
            this.items = items;
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            //1是自己发的（right），0是对面发的（left）

            View view;
            if (viewType == Chat_content.TYPE_TWO) {
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recyclerview_right, parent, false);
                return new Recycler_item_right(view);
            }
            else if(viewType == Chat_content.TYPE_ONE){

                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recyclerview_left, parent, false);
                return new Recycler_item_left(view);
            }
            else{
                return null;
            }

        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            Chat_content item = items.get(position);
            if (item.getType() == 1) {
                ((Recycler_item_right) holder).bindData(item);
            } else {
                ((Recycler_item_left) holder).bindData(item);
            }

        }
        // 提供一个方法来增加数据
        public void addItem(Chat_content item, int position) {
            items.add(position, item);
            notifyItemInserted(position);
        }

        @Override
        public int getItemCount() {
            return items.size();
        }

        @Override
        public int getItemViewType(int position) {
            return items.get(position).getType();
        }


    }

    private void readMessages() {
        try {
            String message;
            while ((message = in.readLine()) != null) {
                Log.v("msg",message);
                if(message.contains("false8")){
                    //提示用户是否开启消息漫游--->将消息暂存在服务器，当对方上线，就将消息发送
                    //发送消息时，对方不在线
                    //提示对方不在线
                    // 设置对话框的标题
                    Log.v("msg","not_here");
                    builder1.setTitle("提示");

                    // 设置对话框的消息内容
                    builder1.setMessage("对方不在线，是否开启消息漫游服务");

                    builder1.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // 用户点击了确定按钮，跳转到消息漫游服务页面
                            //获取想要通信对象 的 id
                            // 创建Intent对象
                            Intent intent = new Intent(ChatActivity.this, CacheActivity.class);
                            intent.putExtra("chat_partner", goal_id);
                            intent.putExtra("chat_name", goal_name);
                            // 启动Activity
                            startActivity(intent);
                            // 关闭当前Activity
                            finish();

                        }
                    });
                    builder1.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // 用户点击了“取消”按钮
                            // 对话框会自动关闭，无需额外处理
                        }
                    });
                    if (!isFinishing()) {
                        runOnUiThread(new Runnable() {//此run方法将由主线程运行
                            @Override
                            public void run() {
                                // 创建并显示对话框
                                AlertDialog dialog = builder1.create();
                                dialog.show();
                            }
                        });
                    }
                    break;

                }else{
                    String[] parts = message.split(",");
                    Content cc = new Content(parts[0],parts[1],parts[2],parts[3],parts[4]);
                    String finalContent = cc.getContent();
                    if(!isFinishing()){
                        runOnUiThread(new Runnable() {//此run方法将由主线程运行

                            @Override
                            public void run() {
                                //此处图片为对话对象的头像，也是从数据库中拿
                                Chat_content p1 = new Chat_content(Chat_content.TYPE_ONE,finalContent,R.drawable.left);
                                // 通知适配器新元素添加
                                adapter.addItem(p1,i);
                                i++;
                                Log.v("msg","receiver");

                            }
                        });
                    }


                }


            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public class Worker implements Runnable {
        private String message;
        public Worker(String message) {
            this.message = message;
        }
        @Override
        public void run() {
            // 使用传递的消息

            out.println(message);

        }
    }


    @Override
    public void onDestroy() {

        super.onDestroy();
        try{
            //关闭输入流，socket连接
            if(socket!=null){
                out.close();
                in.close();
                socket.close();
            }
        }catch(IOException e){
            e.printStackTrace();

        }

    }
}